/* eslint-disable no-restricted-syntax */
/* eslint-disable no-use-before-define */
/* eslint-disable max-len */
import { Ref, computed, ref, SetupContext } from 'vue';
import { ControlTreeViewProps } from '../props/control-tree-view.props';
import { ElementPropertyConfig } from '../entity/property-entity';
import { ControlTreeNode } from '../entity/control-tree-node-entity';
import { BuilderHTMLElement } from '../entity/builder-element';

/** 变更控件树节点后的操作 */
export function changeTreeNode(props: ControlTreeViewProps, context: SetupContext) {
    const styleObject = {} as Record<string, any>;
    /** 代码编辑器绑定的字符串 */
    const monacoCode = ref('');
    /** 当前选中控件实例 */
    const focusedComponentInstance = ref();
    /** mock的json结构 */
    const domJson = {};
    /** 当前右侧显示的视图类型 */
    const bottomTabActive = 'formDesigner';
    /** 属性面板配置数据 */
    let propertyConfig = [];
    /** 属性面板绑定数据 */
    let propertyData: any;
    /** 映射JSON结构映射：<控件id, 控件JSON> */
    let domDgMap: Map<string, any>;
    /** 页面控件实例集合 */
    // FarrisDesignBaseComponent[]
    let componentInstanceList: any;
    const element = ref<HTMLElement>();
    function getUsualPropConfig(propertyData: any): ElementPropertyConfig {
        return {
            categoryId: 'Basic',
            categoryName: '基本信息',
            propertyData: propertyData.module,
            enableCascade: true,
            parentPropertyID: 'module',
            properties: [
                {
                    propertyID: 'metadataId',
                    propertyName: '标识',
                    propertyType: 'string',
                    description: '表单元数据的id',
                    readonly: true
                },
                {
                    propertyID: 'code',
                    propertyName: '编号',
                    propertyType: 'string',
                    description: '表单元数据的编号',
                    readonly: true
                },
                {
                    propertyID: 'name',
                    propertyName: '名称',
                    propertyType: 'string',
                    description: '表单元数据的名称',
                    readonly: true
                },
                {
                    propertyID: 'showType',
                    propertyName: '展示形式',
                    propertyType: 'select', // 目前只支持弹框类卡片模板切换展示形式
                    iterator: [
                        { key: 'modal', value: '弹出表单' },
                        { key: 'page', value: '标签页' },
                        { key: 'sidebar', value: '侧边栏' }
                    ],
                    visible: propertyData.module.templateId === 'modal-card-template',
                    readonly: true
                }
            ], setPropertyRelates(changeObject: any, data, parameters) {
                if (!changeObject) {
                    return;
                }
                switch (changeObject.propertyID) {
                case 'showType': {
                    changeObject.needRefreshForm = true;
                }
                }
            }
        };
    }
    function getPropConfig(propertyData: any): ElementPropertyConfig[] {
        const propertyConfig = [];

        // 常本信息属性
        const usualPropConfig = getUsualPropConfig(propertyData);
        propertyConfig.push(usualPropConfig);

        return propertyConfig;

    }

    /**
     * 更新代码编辑绑定数据
     */
    function updateMonacoCode() {
        // if (focusedComponentInstance.value) {
        //     monacoCode.value = JSON.stringify(focusedComponentInstance.value.component);
        // } else {
        //     monacoCode.value = domJson ? JSON.stringify(domJson) : '';
        // }
        // 是否需要格式化代码
        // formatMonacoCode();
    }
    /**
     * 控件树单击组件节点或控件节点
     */
    function clickControlNode(node: ControlTreeNode, dependentTreeNode?: ControlTreeNode, outsideNodeId?: string) {
        // 场景1：选择控件树上没有的控件
        if (outsideNodeId) {
            const componentInstance = componentInstanceList.find((instance: any) => instance.id === outsideNodeId);
            if (componentInstance) {
                componentInstance.triggerComponentClick();
                updateMonacoCode();
            }
            return;
        }
        // 场景2：有依赖关系的节点，触发依赖节点的点击事件
        if (dependentTreeNode) {
            const componentInstance = componentInstanceList.find((instance: any) => instance.id === dependentTreeNode.data.id);
            if (componentInstance && componentInstance.triggerComponentInsideClick) {
                componentInstance.triggerComponentInsideClick(node);
            }
        } else {
            // 场景3：获取节点对应的控件实例，并触发点击事件，从而显示属性面板
            const focusedComponentInstance = componentInstanceList.find((instance: any) => instance.id === node.data.id);
            if (focusedComponentInstance) {
                focusedComponentInstance.triggerComponentClick();
            }
        }
        updateMonacoCode();
    }

    /** 触发更新属性面板 */
    function updatePropertyPanel(componentInstance: any) {
        // window.suspendChangesOnForm = true;
        if (!componentInstance || !componentInstance.component) {
            propertyConfig = [];
            propertyData = {};

            // window.suspendChangesOnForm = false;
            // return;
        }

        if (componentInstance.getPropertyConfig) {
            propertyConfig = componentInstance.getPropertyConfig() || [];
        } else {
            propertyConfig = [];
        }
        propertyData = componentInstance.component;
    }

    /** 根据代码编辑器修改后的数据，更新表单DOM JSON */
    function updateDOMByMonacoCode() {
        const newDomJson = JSON.parse(monacoCode.value);

        // 修改控件domDgMap
        if (focusedComponentInstance.value && focusedComponentInstance.value.type !== 'Frame') {
            const focusedId = focusedComponentInstance.value.id;
            // const oldDomJson = domService.domDgMap.get(focusedComponentInstance.id);
            // if (oldDomJson) {
            //     Object.assign(oldDomJson, newDomJson);
            //     updateChildContentsDgMap(newDomJson);
            // }
        } else {
            Object.assign(domJson, newDomJson);
        }

        // 校验DOM中viewmodel和component是否一一对应。主要用于手动修改代码编辑器后，导致的编译失败问题
        // const validationServ = new DomValidtionService(domService, webCmdService, msgService);
        // if (!validationServ.checkComponentAndViewModelCanMatch(domJson)) {
        //     return false;
        // }
        return true;
    }
    /** 点击左侧控件树 */
    function onComponentClicked(e?: PointerEvent) {
        const designId = `${e}-design-item`;
        const curSelectedElement = document.getElementById(designId) as any;

        if (designId) {
            const currentSelectedElements = document.getElementsByClassName('dgComponentSelected') as HTMLCollectionOf<BuilderHTMLElement>;

            // 重复点击
            const duplicateClick = currentSelectedElements && currentSelectedElements.length === 1 && currentSelectedElements[0] === curSelectedElement;
            if (!duplicateClick) {
                for (const element of Array.from(currentSelectedElements)) {
                    element.classList.remove('dgComponentSelected');
                    if (element.componentInstance && element.componentInstance.afterComponentCancelClicked) {
                        element.componentInstance.afterComponentCancelClicked(e);
                    }
                }
                curSelectedElement?.classList.add('dgComponentSelected');
                const propertyData = curSelectedElement?.componentInstance.value.schema;
                const check = curSelectedElement.componentInstance.value.getPropConfig();
                console.log('属性面板返回值',check);
                return check;
                // if (afterComponentClicked) {
                //     afterComponentClicked(e);
                // }
            }
            // setPositionOfBtnGroup();
        }
        // emit('componentClicked', { e, componentInstance: this });
    }
    /** 点击控件树顶层表单frame节点 */
    function clickFrameTreeNode(node: ControlTreeNode) {
        // window.suspendChangesOnForm = true;
        focusedComponentInstance.value = null;

        // 触发显示属性面板
        const customPropConfig = getPropConfig(domJson);
        propertyConfig = customPropConfig;
        propertyData = domJson;

        // 移除可视化区域的选定边框
        const elements = document.getElementsByClassName('dgComponentSelected') as HTMLCollectionOf<BuilderHTMLElement>;
        if (elements && elements.length > 0) {
            for (const element of Array.from(elements)) {
                element.classList.remove('dgComponentSelected');
                if (element.componentInstance && element.componentInstance.afterComponentCancelClicked) {
                    element.componentInstance.afterComponentCancelClicked(null);
                }
            }
        }
    }
    /**
     * 变更控件树节点
     * @param node 选中的树节点
     */
    function changeControlTreeNode(data: { treeNode: any; dependentTreeNode?: ControlTreeNode }) {
        const node = data.treeNode;
        // if (!node) {
        //     updatePropertyPanel(null);
        //     return;
        // }
        const { dependentTreeNode } = data;
        switch (node.type) {
        // 表单控件节点
        case 'Control':
        case 'Component': {
            // if (!updateDOMByMonacoCode()) {
            //     return;
            // }
            clickControlNode(node, dependentTreeNode);
            break;
        }
        // 顶层frame节点
        case 'Frame': {
            if (!updateDOMByMonacoCode()) {
                return;
            }
            clickFrameTreeNode(node);
            break;
        }
        }
    }

    return {
        changeControlTreeNode,
        onComponentClicked
    };
}
